package com.dong.c05_nio_group_chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <h1></h1>
 *
 * @author : dzj
 * @create: 2020-03-18 18:06
 */
public class GroupChatClient {
    private static final int PORT= 6667;
    private static final String HOST= "localhost";
    private Selector selector;
    private SocketChannel socketChannel;
    private String username= "";

    public GroupChatClient() {
        try {
            selector=Selector.open();
            socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
            //设置非阻塞
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            //
            username=socketChannel.getLocalAddress().toString().substring(1);
            System.out.println("客户端"+username +"就绪...");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void sendMsg(String msg) {
        try {
            msg=username+" 说: "+msg;
            socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void readMsg() {
        try {
            int count = selector.select(100);
            if(count==0) {
                System.out.println("没有可用通道");
                return;
            }else {
                System.out.println("读取消息: 发生事件");
            }
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while(iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                SocketChannel channel = (SocketChannel) selectionKey.channel();
                if(selectionKey.isReadable()) {
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    channel.read(buffer);
                    String msg = new String(buffer.array());
                    System.out.println("客户端接收消息: "+ msg.trim());
                    iterator.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void close() {
        try {
            socketChannel.close();
            selector.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socketChannel.close();
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try {
            GroupChatClient client = new GroupChatClient();
          final   ExecutorService executorService = Executors.newFixedThreadPool(2);
            executorService.execute(()-> {
                //read
                try {
                    while (true) {
                        client.readMsg();
                        Thread.sleep(3000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            executorService.execute(()-> {
                //write
                try {
                    while (true) {
                        String msg = br.readLine();
                        if(msg.equals("quit!")) {
                            System.out.println("服务器端断开连接");
                            client.close();
                            executorService.shutdown();
                        }
                        System.out.println("客户端 [ "+client.username+" ] 发送消息:"+msg);
                        client.sendMsg(msg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }finally {

        }
    }
}
